import wepy from 'wepy'

export default class Home extends wepy.mixin {
  data = {
    address: null,
    cart: [],
    token: ''
  }

  methods = {
    // 选择收货地址
    async chooseAddress () {
      const res = await wepy.chooseAddress().catch(err=>err)
      if(res.errMsg !== 'chooseAddress:ok') return wepy.baseToast('亲，取消选择地址了')
      wepy.baseToast('亲，选择地址成功')
      this.address = res 
      wepy.setStorageSync('address',res)
    },

    // 获取微信用户信息，同时也是点击了登录按钮
    async getWxUser (e) {
      const { encryptedData, iv, rawData, signature } = e.detail 
      const { code } = await wepy.login()
      const {data: res} = await wepy.post('/users/wxlogin',{
        encryptedData, iv, rawData, signature, code
      })

      if(res.meta.status !== 200) return wepy.baseToast('抱歉，登录失败了，重试')
      wepy.baseToast('亲，登录成功')
      this.token = res.message.token
      wepy.setStorageSync('token',this.token)
      this.$apply()
    },

    // 支付
    async submitPayOrder () {
      // (1). 创建订单
      // (1) 01-参数整理
      var goods = this.cart.map(item=>{
        return { 
          goods_id: item.id, 
          goods_number: item.count, 
          goods_price: item.price
        }
      })
      var createData = {
        order_price: this.totalPrice,
        consignee_addr: this.addressStr,
        order_detail: JSON.stringify(this.cart),
        goods
      }
      // (1) 02- 发送请求
      const { data: createOrderRes } = await wepy.post('/my/orders/create',createData)
      if(createOrderRes.meta.status !== 200) return wepy.baseToast('支付失败，请重试')

      // (2). 预支付
      const { data: beforePay } = await wepy.post('/my/orders/req_unifiedorder',{
        order_number: createOrderRes.message.order_number
      })
      if(beforePay.meta.status !== 200) return wepy.baseToast('支付失败，请重试')

      // (3). 01-唤起微信原生支付
      const payRes = await wepy.requestPayment(beforePay.message.pay).catch(err=>err)
      // (3). 02-判断支付状态 
      if(payRes.errMsg !== 'requestPayment:ok') return wepy.baseToast('取消支付')
      wepy.baseToast('支付成功')
      wepy.navigateTo({
        url: '/pages/order/list'
      })
    }
  }

  computed = {
    // 这个计算属性是控制是否显示选择收货地址
    isShowChooseAddress () {
      return !this.address
    },

    // 收货地址信息
    addressStr () {
      if(this.address === null) return ''
      const { provinceName, cityName, countyName, detailInfo } = this.address
      return provinceName+cityName+countyName+detailInfo
    },

    // 计算登录和支付订单按需显示
    isShowLogin () {
      return !this.token
    },

    // 计算确认订单总价
    totalPrice () {
      var total = 0
      this.cart.forEach(item=>{
        total+=item.count*item.price
      })
      return total*100
    }
  }

  onLoad () {
    this.address = wepy.getStorageSync('address') || null
    // 过滤iCheck为true的 构成一个新的数组
    this.cart = this.$parent.globalData.cart.filter(x=>x.isCheck)
    // 获取本地的token存储data中
    this.token = wepy.getStorageSync('token') || ''
  }
}